

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="叶飞">
  <meta name="keywords" content="">
  
    <meta name="description" content="1 httprouter简介   微框架？   通过前缀树trie提高性能，自定义请求路由分发策略   代码核心：net&#x2F;http -&gt; http.Handler接口   Features: 来自项目的README  only explicit matches: 精确匹配 stop caring about trailing slashes: 不关注尾部斜杠 Path auto-corre">
<meta property="og:type" content="article">
<meta property="og:title" content="httprouter">
<meta property="og:url" content="http://example.com/2022/04/18/20220418-httprouter/index.html">
<meta property="og:site_name" content="博客">
<meta property="og:description" content="1 httprouter简介   微框架？   通过前缀树trie提高性能，自定义请求路由分发策略   代码核心：net&#x2F;http -&gt; http.Handler接口   Features: 来自项目的README  only explicit matches: 精确匹配 stop caring about trailing slashes: 不关注尾部斜杠 Path auto-corre">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/img/20220418-httprouter.assets/trie_eg.jpg">
<meta property="og:image" content="http://example.com/img/20220418-httprouter.assets/webp.webp">
<meta property="og:image" content="http://example.com/img/20220418-httprouter.assets/webp.webp">
<meta property="article:published_time" content="2022-04-18T04:46:47.000Z">
<meta property="article:modified_time" content="2022-04-18T14:09:24.447Z">
<meta property="article:author" content="叶飞">
<meta property="article:tag" content="前缀树">
<meta property="article:tag" content="路由">
<meta property="article:tag" content="httprouter">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://example.com/img/20220418-httprouter.assets/trie_eg.jpg">
  
  
  
  <title>httprouter - 博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>No Tomorrow</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="httprouter"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        叶飞
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-04-18 12:46" pubdate>
          星期一, 四月 18日 2022, 12:46 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          <!-- compatible with older versions-->
          19k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          <!-- compatible with older versions-->
          162 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">httprouter</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="1-httprouter简介"><a class="markdownIt-Anchor" href="#1-httprouter简介"></a> 1 httprouter简介</h2>
<ul>
<li>
<p>微框架？</p>
</li>
<li>
<p>通过前缀树trie提高性能，自定义请求路由分发策略</p>
</li>
<li>
<p>代码核心：net/http -&gt; http.Handler接口</p>
</li>
<li>
<p>Features: 来自项目的README</p>
<ul>
<li>only explicit matches: 精确匹配</li>
<li>stop caring about trailing slashes: 不关注尾部斜杠</li>
<li>Path auto-correction: 路由自动更正，包括检测丢失或多余的斜线/</li>
<li>parameters in your routing pattern: 动态路由匹配。为路径段命名，路由器可以将动态值解析并传递</li>
<li>zero garbage: 零垃圾。 匹配和调度过程产生零字节的垃圾。</li>
<li>best performance</li>
<li>no more server crashed:</li>
<li>perfect for apis: <strong>restful apis</strong></li>
</ul>
</li>
<li>
<p>实现原理及优势：来自项目README/How does it work</p>
<ul>
<li>前缀树、基数树。 trie/ radix tree</li>
</ul>
<figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs markdown">Priority   Path             Handle<br>9          \                <span class="hljs-emphasis">*&lt;1&gt;</span><br><span class="hljs-emphasis">3          ├s               nil</span><br><span class="hljs-emphasis">2          |├earch\         *</span>&lt;2&gt;<br>1          |└upport\        <span class="hljs-emphasis">*&lt;3&gt;</span><br><span class="hljs-emphasis">2          ├blog\           *</span>&lt;4&gt;<br>1          |    └:post      nil<br>1          |         └\     <span class="hljs-emphasis">*&lt;5&gt;</span><br><span class="hljs-emphasis">2          ├about-us\       *</span>&lt;6&gt;<br>1          |        └team\  <span class="hljs-emphasis">*&lt;7&gt;</span><br><span class="hljs-emphasis">1          └contact\        *</span>&lt;8&gt;<br></code></pre></td></tr></table></figure>
<ul>
<li>Moreover the router manages a separate tree for every request method.</li>
<li>实现<code>http.Handler</code>接口</li>
<li>链接操作，可以添加中间件middleware</li>
<li>路由组：Group? 好像不是</li>
<li>Basic Authentication</li>
</ul>
</li>
</ul>
<h2 id="2-为什么使用httprouter"><a class="markdownIt-Anchor" href="#2-为什么使用httprouter"></a> 2 为什么使用httprouter</h2>
<blockquote>
<p>优势</p>
</blockquote>
<h3 id="21-nethttp的不足"><a class="markdownIt-Anchor" href="#21-nethttp的不足"></a> 2.1 net/http的不足</h3>
<ul>
<li>不能单独的对请求方法(POST,GET等)注册特定的处理函数</li>
<li>不支持<strong>路由变量参数</strong>【动态路由】</li>
<li>不能自动对Path进行校准</li>
<li>性能一般、扩展性不足</li>
</ul>
<h3 id="22-httprouter的便利"><a class="markdownIt-Anchor" href="#22-httprouter的便利"></a> 2.2 httprouter的便利</h3>
<ul>
<li>仅支持<code>精确匹配</code>，及只匹配一个模式或不会匹配到任何模式。相对于其他一些mux，例如go原生的 <a target="_blank" rel="noopener" href="http://golang.org/pkg/net/http/#ServeMux">http.ServerMux</a>, 会使得一个请求URL匹配多个模式，从而需要有优先级顺序，例如最长匹配、最先匹配等等。</li>
<li>不需要关心URL<code>结尾的斜杠</code></li>
<li>路径自动归一化和矫正</li>
<li>零内存分配、高性能</li>
</ul>
<h2 id="3-httprouter的项目结构"><a class="markdownIt-Anchor" href="#3-httprouter的项目结构"></a> 3 httprouter的项目结构</h2>
<ul>
<li>tree.go</li>
<li>router.go</li>
<li>path.go</li>
</ul>
<p>httprouter的路由冲突问题！！！！！</p>
<h2 id="4-routergo"><a class="markdownIt-Anchor" href="#4-routergo"></a> 4 router.go</h2>
<h3 id="41-关键结构体"><a class="markdownIt-Anchor" href="#41-关键结构体"></a> 4.1 关键结构体</h3>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// Router is a http.Handler which can be used to dispatch requests to different</span><br><span class="hljs-comment">// handler functions via configurable routes</span><br><span class="hljs-keyword">type</span> Router <span class="hljs-keyword">struct</span> &#123;<br>	<span class="hljs-comment">// 构建多个树</span><br>	trees <span class="hljs-keyword">map</span>[<span class="hljs-type">string</span>]*node<br><br>	paramsPool sync.Pool<br>	maxParams  <span class="hljs-type">uint16</span><br><br>	<span class="hljs-comment">// If enabled, adds the matched route path onto the http.Request context</span><br>	<span class="hljs-comment">// before invoking the handler.</span><br>	<span class="hljs-comment">// The matched route path is only added to handlers of routes that were</span><br>	<span class="hljs-comment">// registered when this option was enabled.</span><br>	<span class="hljs-comment">// 如果是true，会把匹配到的path在调用handler之前加到context里</span><br>  	<span class="hljs-comment">// 只有当这个值是true的时候，匹配到的path才会被加到handler的routes里面	</span><br>	SaveMatchedRoutePath <span class="hljs-type">bool</span><br><br>	<span class="hljs-comment">// Enables automatic redirection if the current route can&#x27;t be matched but a</span><br>	<span class="hljs-comment">// handler for the path with (without) the trailing slash exists.</span><br>	<span class="hljs-comment">// For example if /foo/ is requested but a route only exists for /foo, the</span><br>	<span class="hljs-comment">// client is redirected to /foo with http status code 301 for GET requests</span><br>	<span class="hljs-comment">// and 308 for all other request methods.</span><br>	RedirectTrailingSlash <span class="hljs-type">bool</span><br><br>	<span class="hljs-comment">// If enabled, the router tries to fix the current request path, if no</span><br>	<span class="hljs-comment">// handle is registered for it.</span><br>	<span class="hljs-comment">// First superfluous path elements like ../ or // are removed.</span><br>	<span class="hljs-comment">// Afterwards the router does a case-insensitive lookup of the cleaned path.</span><br>	<span class="hljs-comment">// If a handle can be found for this route, the router makes a redirection</span><br>	<span class="hljs-comment">// to the corrected path with status code 301 for GET requests and 308 for</span><br>	<span class="hljs-comment">// all other request methods.</span><br>	<span class="hljs-comment">// For example /FOO and /..//Foo could be redirected to /foo.</span><br>	<span class="hljs-comment">// RedirectTrailingSlash is independent of this option.</span><br>	<span class="hljs-comment">// 如果匹配不上,尝试修复path,比如删除../ // </span><br>	<span class="hljs-comment">// 对于Get返回301 其他返回303 </span><br>	<span class="hljs-comment">// 301- 永久移动   302临时移动</span><br>	RedirectFixedPath <span class="hljs-type">bool</span><br><br>	<span class="hljs-comment">// If enabled, the router checks if another method is allowed for the</span><br>	<span class="hljs-comment">// current route, if the current request can not be routed.</span><br>	<span class="hljs-comment">// If this is the case, the request is answered with &#x27;Method Not Allowed&#x27;</span><br>	<span class="hljs-comment">// and HTTP status code 405.</span><br>	<span class="hljs-comment">// If no other Method is allowed, the request is delegated to the NotFound</span><br>	<span class="hljs-comment">// handler.</span><br>	<span class="hljs-comment">// 当当前请求无法被路由时,检查是否有其他方法被允许 </span><br>	<span class="hljs-comment">// 405 方法不允许</span><br>	HandleMethodNotAllowed <span class="hljs-type">bool</span><br><br>	<span class="hljs-comment">// If enabled, the router automatically replies to OPTIONS requests.</span><br>	<span class="hljs-comment">// Custom OPTIONS handlers take priority over automatic replies.</span><br>	<span class="hljs-comment">// 用户自定义的handler优先级更高,路由器自动回复OPTIONS</span><br>	HandleOPTIONS <span class="hljs-type">bool</span><br><br>	<span class="hljs-comment">// An optional http.Handler that is called on automatic OPTIONS requests.</span><br>	<span class="hljs-comment">// The handler is only called if HandleOPTIONS is true and no OPTIONS</span><br>	<span class="hljs-comment">// handler for the specific path was set.</span><br>	<span class="hljs-comment">// The &quot;Allowed&quot; header is set before calling the handler.</span><br>	GlobalOPTIONS http.Handler  <span class="hljs-comment">//if HandleOPTIONS is true and no OPTIONS</span><br><br>	<span class="hljs-comment">// Cached value of global (*) allowed methods</span><br>	globalAllowed <span class="hljs-type">string</span><br><br>	<span class="hljs-comment">// Configurable http.Handler which is called when no matching route is</span><br>	<span class="hljs-comment">// found. If it is not set, http.NotFound is used.</span><br>	NotFound http.Handler   <span class="hljs-comment">// http.NotFound 标准库里面的</span><br><br>	<span class="hljs-comment">// Configurable http.Handler which is called when a request</span><br>	<span class="hljs-comment">// cannot be routed and HandleMethodNotAllowed is true.</span><br>	<span class="hljs-comment">// If it is not set, http.Error with http.StatusMethodNotAllowed is used.</span><br>	<span class="hljs-comment">// The &quot;Allow&quot; header with allowed request methods is set before the handler</span><br>	<span class="hljs-comment">// is called.</span><br>	<span class="hljs-comment">// 当一个请求是不被允许的，并且上面的 HandleMethodNotAllowed 设置为 ture 的时候，</span><br>  	<span class="hljs-comment">// 如果这个参数没有设置，将使用状态为 with http.StatusMethodNotAllowed 的 http.Error</span><br>  	<span class="hljs-comment">// 在 handler 被调用以前，为允许请求的方法设置 &quot;Allow&quot; header</span><br>	MethodNotAllowed http.Handler<br><br>	<span class="hljs-comment">// Function to handle panics recovered from http handlers.</span><br>	<span class="hljs-comment">// It should be used to generate a error page and return the http error code</span><br>	<span class="hljs-comment">// 500 (Internal Server Error).</span><br>	<span class="hljs-comment">// The handler can be used to keep your server from crashing because of</span><br>	<span class="hljs-comment">// unrecovered panics.</span><br>		<span class="hljs-comment">// panic recover</span><br>	PanicHandler <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(http.ResponseWriter, *http.Request, <span class="hljs-keyword">interface</span>&#123;&#125;)</span></span><br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="42-核心函数handle"><a class="markdownIt-Anchor" href="#42-核心函数handle"></a> 4.2 核心函数Handle:</h3>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><code class="hljs go"><br><span class="hljs-comment">// Handle registers a new request handle with the given path and method.</span><br><span class="hljs-comment">//</span><br><span class="hljs-comment">// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut</span><br><span class="hljs-comment">// functions can be used.</span><br><span class="hljs-comment">//</span><br><span class="hljs-comment">// This function is intended for bulk loading and to allow the usage of less</span><br><span class="hljs-comment">// frequently used, non-standardized or custom methods (e.g. for internal</span><br><span class="hljs-comment">// communication with a proxy).</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r *Router)</span></span> Handle(method, path <span class="hljs-type">string</span>, handle Handle) &#123;<br>	varsCount := <span class="hljs-type">uint16</span>(<span class="hljs-number">0</span>)<br><br>	<span class="hljs-keyword">if</span> method == <span class="hljs-string">&quot;&quot;</span> &#123;<br>		<span class="hljs-built_in">panic</span>(<span class="hljs-string">&quot;method must not be empty&quot;</span>)<br>	&#125;<br>	<span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(path) &lt; <span class="hljs-number">1</span> || path[<span class="hljs-number">0</span>] != <span class="hljs-string">&#x27;/&#x27;</span> &#123;<br>		<span class="hljs-built_in">panic</span>(<span class="hljs-string">&quot;path must begin with &#x27;/&#x27; in path &#x27;&quot;</span> + path + <span class="hljs-string">&quot;&#x27;&quot;</span>)<br>	&#125;<br>	<span class="hljs-keyword">if</span> handle == <span class="hljs-literal">nil</span> &#123;<br>		<span class="hljs-built_in">panic</span>(<span class="hljs-string">&quot;handle must not be nil&quot;</span>)<br>	&#125;<br><br>	<span class="hljs-keyword">if</span> r.SaveMatchedRoutePath &#123;<br>		varsCount++<br>		handle = r.saveMatchedRoutePath(path, handle)<br>	&#125;<br><br>	<span class="hljs-keyword">if</span> r.trees == <span class="hljs-literal">nil</span> &#123;<br>		r.trees = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">map</span>[<span class="hljs-type">string</span>]*node)<br>	&#125;<br><span class="hljs-comment">// 对应的方法节点 -&gt;&gt;这说明每个方法都有一棵radix tree</span><br>	root := r.trees[method]<br>	<span class="hljs-keyword">if</span> root == <span class="hljs-literal">nil</span> &#123;<br>		root = <span class="hljs-built_in">new</span>(node)<br>		r.trees[method] = root<br><br>		r.globalAllowed = r.allowed(<span class="hljs-string">&quot;*&quot;</span>, <span class="hljs-string">&quot;&quot;</span>)<br>	&#125;<br>	<span class="hljs-comment">/*</span><br><span class="hljs-comment">	树中添加路由</span><br><span class="hljs-comment">	*/</span><br>	root.addRoute(path, handle)<br><br>	<span class="hljs-comment">// Update maxParams</span><br>	<span class="hljs-keyword">if</span> paramsCount := countParams(path); paramsCount+varsCount &gt; r.maxParams &#123;<br>		r.maxParams = paramsCount + varsCount<br>	&#125;<br><br>	<span class="hljs-comment">// Lazy-init paramsPool alloc func</span><br>	<span class="hljs-keyword">if</span> r.paramsPool.New == <span class="hljs-literal">nil</span> &amp;&amp; r.maxParams &gt; <span class="hljs-number">0</span> &#123;<br>		r.paramsPool.New = <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> <span class="hljs-keyword">interface</span>&#123;&#125; &#123;<br>			ps := <span class="hljs-built_in">make</span>(Params, <span class="hljs-number">0</span>, r.maxParams)<br>			<span class="hljs-keyword">return</span> &amp;ps<br>		&#125;<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>type Handle func(http.ResponseWriter, *http.Request, Params)</p>
<p>比http.Handle多了Params参数,支持路径参数绑定—&gt;动态路由</p>
</blockquote>
<ul>
<li>参数通过:<code>Params.ByName(&quot;name&quot;)</code>获取</li>
</ul>
<h2 id="5-treego"><a class="markdownIt-Anchor" href="#5-treego"></a> 5 tree.go</h2>
<blockquote>
<ul>
<li>
<p>addRoute方法为切入口</p>
</li>
<li>
<p>定义前缀树的结构</p>
</li>
</ul>
</blockquote>
<p><img src="/img/20220418-httprouter.assets/trie_eg.jpg" srcset="/img/loading.gif" lazyload alt="trie tree"></p>
<ul>
<li>动态路由
<ul>
<li>参数匹配<code>:</code> 如<code>/p/:lang/doc</code>，可以匹配<code>/p/c/doc /p/go/doc</code></li>
<li>通配wildcard<code>*</code> 如<code>/static/*filepath</code>，可以匹配<code>/static/fav.ico</code>和<code>/static/js/jQuery.js</code></li>
</ul>
</li>
</ul>
<h3 id="51-node"><a class="markdownIt-Anchor" href="#51-node"></a> 5.1 node</h3>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">type</span> node <span class="hljs-keyword">struct</span> &#123;<br>	<span class="hljs-comment">// 路径</span><br>	path      <span class="hljs-type">string</span><br>	<span class="hljs-comment">// 相当于下级节点的索引</span><br>    <span class="hljs-comment">// child的首字母  见addRoute()部分可知</span><br>	indices   <span class="hljs-type">string</span><br>	<span class="hljs-comment">// child是否包含通配符  </span><br>	wildChild <span class="hljs-type">bool</span><br>	<span class="hljs-comment">// 节点类型：root param catchALL</span><br>	nType     nodeType<br>	<span class="hljs-comment">// 优先级  这个一般在一个请求匹配多个模式时用的吧</span><br>	<span class="hljs-comment">// 根据下文,优先级和节点在children数组中的位置有关</span><br>    <span class="hljs-comment">// 优先级越大,越往前,等于子节点的数量+1(当前节点)</span><br>    <span class="hljs-comment">// insertChild方法可知</span><br>	priority  <span class="hljs-type">uint32</span><br>	<span class="hljs-comment">// 树结构嘛，子树</span><br>	children  []*node<br>	<span class="hljs-comment">// router.go 实现http.Handler接口</span><br>    <span class="hljs-comment">// 似乎只有叶子节点 handle!=nil </span><br>	handle    Handle<br>&#125;<br><span class="hljs-comment">// 节点类型如下</span><br><span class="hljs-keyword">type</span> nodeType <span class="hljs-type">uint8</span><br><br><span class="hljs-keyword">const</span> (<br>	static nodeType = <span class="hljs-literal">iota</span> <span class="hljs-comment">// default  0</span><br>	root   <span class="hljs-comment">// 1</span><br>    <span class="hljs-comment">///user/&#123;id&#125;，id 就是一个参数节点</span><br>	param   <span class="hljs-comment">// 2</span><br>   	<span class="hljs-comment">// 叶子节点？？？</span><br>    <span class="hljs-comment">// 通配符??</span><br>    <span class="hljs-comment">// 以*结尾的路由</span><br>	catchAll   <span class="hljs-comment">// 3</span><br>)<br></code></pre></td></tr></table></figure>
<h3 id="52-前缀树trie和基数树radix-tree的区别"><a class="markdownIt-Anchor" href="#52-前缀树trie和基数树radix-tree的区别"></a> 5.2 前缀树(Trie)和基数树（Radix Tree)的区别</h3>
<p><img src="/img/20220418-httprouter.assets/webp.webp" srcset="/img/loading.gif" lazyload alt="trie vs radix"></p>
<p>trie又叫前缀树，是一个多叉树，广泛应用于字符串搜索，每个树节点存储一个字符，从根节点到任意一个叶子结点串起来就是一个字符串；</p>
<p>radix tree是优化之后的前缀树，对空间进一步压缩。</p>
<h3 id="53-具体实现核心函数"><a class="markdownIt-Anchor" href="#53-具体实现核心函数"></a> 5.3 具体实现–核心函数</h3>
<blockquote>
<p>func (n *node) addRoute(path string, handle Handle)</p>
<p>func (n *node) getValue(path string, params func() *Params) (handle Handle, ps *Params, tsr bool)</p>
</blockquote>
<ul>
<li>path : 是一个完全路径 fullpath</li>
</ul>
<p><img src="/img/20220418-httprouter.assets/webp.webp" srcset="/img/loading.gif" lazyload alt="img"></p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br><span class="line">368</span><br><span class="line">369</span><br><span class="line">370</span><br><span class="line">371</span><br><span class="line">372</span><br><span class="line">373</span><br><span class="line">374</span><br><span class="line">375</span><br><span class="line">376</span><br><span class="line">377</span><br><span class="line">378</span><br><span class="line">379</span><br><span class="line">380</span><br><span class="line">381</span><br><span class="line">382</span><br><span class="line">383</span><br><span class="line">384</span><br><span class="line">385</span><br><span class="line">386</span><br><span class="line">387</span><br><span class="line">388</span><br><span class="line">389</span><br><span class="line">390</span><br><span class="line">391</span><br><span class="line">392</span><br><span class="line">393</span><br><span class="line">394</span><br><span class="line">395</span><br><span class="line">396</span><br><span class="line">397</span><br><span class="line">398</span><br><span class="line">399</span><br><span class="line">400</span><br><span class="line">401</span><br><span class="line">402</span><br><span class="line">403</span><br><span class="line">404</span><br><span class="line">405</span><br><span class="line">406</span><br><span class="line">407</span><br><span class="line">408</span><br><span class="line">409</span><br><span class="line">410</span><br><span class="line">411</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-comment">// addRoute adds a node with the given handle to the path.</span><br><span class="hljs-comment">// Not concurrency-safe!   非并发安全.....</span><br><span class="hljs-comment">// addRoute: 添加给定handle的node到path</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(n *node)</span></span> addRoute(path <span class="hljs-type">string</span>, handle Handle) &#123;<br>	fullPath := path<br>	<span class="hljs-comment">// 优先级----也就是在child中应该呆的位置</span><br>	n.priority++<br><br>	<span class="hljs-comment">// Empty tree</span><br>	<span class="hljs-comment">// n.path 表示当前节点的路径 / /p  /p/p1  这就是三个节点,且显然是上下级关系</span><br>	<span class="hljs-keyword">if</span> n.path == <span class="hljs-string">&quot;&quot;</span> &amp;&amp; n.indices == <span class="hljs-string">&quot;&quot;</span> &#123;<br>		<span class="hljs-comment">// 发生函数调用</span><br>		n.insertChild(path, fullPath, handle)<br>		n.nType = root<br>		<span class="hljs-keyword">return</span><br>	&#125;<br><br>	<span class="hljs-comment">// 否则,进行正常的节点插入</span><br>walk:<br>	<span class="hljs-keyword">for</span> &#123;<br>		<span class="hljs-comment">// Find the longest common prefix.</span><br>		<span class="hljs-comment">// This also implies that the common prefix contains no &#x27;:&#x27; or &#x27;*&#x27;</span><br>		<span class="hljs-comment">// since the existing key can&#x27;t contain those chars.</span><br>		<span class="hljs-comment">// 寻找path 和 上一级n.path的公共前缀</span><br>		<span class="hljs-comment">// 公共前缀不包含通配符 &quot;:&quot;  &quot;*&quot;</span><br>		i := longestCommonPrefix(path, n.path)<br><br>		<span class="hljs-comment">// Split edge</span><br>		<span class="hljs-keyword">if</span> i &lt; <span class="hljs-built_in">len</span>(n.path) &#123;<br>			<span class="hljs-comment">// 发生分裂,发现原有节点可以分裂</span><br>			<span class="hljs-comment">// 产生一个子节点</span><br>			<span class="hljs-comment">// 继承.相当于在n和原有children之间插入一个child</span><br>			child := node&#123;<br>				<span class="hljs-comment">// 子节点的路径:  不保存公共前缀</span><br>				path:      n.path[i:],<br>				wildChild: n.wildChild,<br>				nType:     static,<br>				indices:   n.indices,<br>				<span class="hljs-comment">// 继承.相当于在n和原有children之间插入一个child</span><br>				children:  n.children,<br>				handle:    n.handle,<br>				priority:  n.priority - <span class="hljs-number">1</span>,<br>			&#125;<br>			<span class="hljs-comment">// 插入 </span><br>			n.children = []*node&#123;&amp;child&#125;<br>			<span class="hljs-comment">// []byte for proper unicode char conversion, see #65</span><br>			<span class="hljs-comment">// 现在n只有一个child了吧,所以indices只有一个字符 也就是child第一个字符</span><br>			n.indices = <span class="hljs-type">string</span>([]<span class="hljs-type">byte</span>&#123;n.path[i]&#125;)<br>			n.path = path[:i]<br>			n.handle = <span class="hljs-literal">nil</span><br>			n.wildChild = <span class="hljs-literal">false</span><br>		&#125;<br><br>		<span class="hljs-comment">// Make new node a child of this node</span><br>		<span class="hljs-comment">// i&gt; n.path  说明path(fullpath)包含n.path</span><br>		<span class="hljs-comment">// 此时传入的路径为n.path的子节点</span><br>		<span class="hljs-keyword">if</span> i &lt; <span class="hljs-built_in">len</span>(path) &#123;<br>			<span class="hljs-comment">// 舍弃公共前缀部分,每个节点只保存独立的路径子段</span><br>			path = path[i:]<br>			<span class="hljs-comment">// 如果包含通配符</span><br>			<span class="hljs-keyword">if</span> n.wildChild &#123;<br>				<span class="hljs-comment">// ?</span><br>				n = n.children[<span class="hljs-number">0</span>] <br>				n.priority++<br><br>				<span class="hljs-comment">// Check if the wildcard matches</span><br>				<span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(path) &gt;= <span class="hljs-built_in">len</span>(n.path) &amp;&amp; n.path == path[:<span class="hljs-built_in">len</span>(n.path)] &amp;&amp;<br>					<span class="hljs-comment">// Adding a child to a catchAll is not possible</span><br>					<span class="hljs-comment">// catchAll 是叶子节点???</span><br>					n.nType != catchAll &amp;&amp;<br>					<span class="hljs-comment">// Check for longer wildcard, e.g. :name and :names</span><br>					(<span class="hljs-built_in">len</span>(n.path) &gt;= <span class="hljs-built_in">len</span>(path) || path[<span class="hljs-built_in">len</span>(n.path)] == <span class="hljs-string">&#x27;/&#x27;</span>) &#123;<br>					<span class="hljs-keyword">continue</span> walk<br>				&#125; <span class="hljs-keyword">else</span> &#123;<br>					<span class="hljs-comment">// Wildcard conflict</span><br>					<span class="hljs-comment">// 通配符冲突?</span><br><span class="hljs-comment">// GET /articles/info</span><br><span class="hljs-comment">// GET /articles/:articleID</span><br>					pathSeg := path<br>					<span class="hljs-keyword">if</span> n.nType != catchAll &#123;<br>						<span class="hljs-comment">// 分割为最多2个子串</span><br>						<span class="hljs-comment">// 从前往后,优先匹配的感觉</span><br>						<span class="hljs-comment">// 例子 &quot;a,b,c&quot; 2  -&gt; [&quot;a&quot;,&quot;b,c&quot;]</span><br>						pathSeg = strings.SplitN(pathSeg, <span class="hljs-string">&quot;/&quot;</span>, <span class="hljs-number">2</span>)[<span class="hljs-number">0</span>]<br>						<span class="hljs-comment">// pathSeg []string</span><br>					&#125;<br>					<span class="hljs-comment">// 所以,此时pathSeg[0]/pathSeg是待插入节点的path???</span><br>					<span class="hljs-comment">// 现有的路由规则</span><br>					prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path<br>					<span class="hljs-built_in">panic</span>(<span class="hljs-string">&quot;&#x27;&quot;</span> + pathSeg +<br>						<span class="hljs-string">&quot;&#x27; in new path &#x27;&quot;</span> + fullPath +<br>						<span class="hljs-string">&quot;&#x27; conflicts with existing wildcard &#x27;&quot;</span> + n.path +<br>						<span class="hljs-string">&quot;&#x27; in existing prefix &#x27;&quot;</span> + prefix +<br>						<span class="hljs-string">&quot;&#x27;&quot;</span>)<br>				&#125;<br>			&#125;<br><br>			idxc := path[<span class="hljs-number">0</span>]<br><br>			<span class="hljs-comment">// &#x27;/&#x27; after param</span><br>			<span class="hljs-keyword">if</span> n.nType == param &amp;&amp; idxc == <span class="hljs-string">&#x27;/&#x27;</span> &amp;&amp; <span class="hljs-built_in">len</span>(n.children) == <span class="hljs-number">1</span> &#123;<br>				<span class="hljs-comment">// 迭代向下?</span><br>				n = n.children[<span class="hljs-number">0</span>]<br>				n.priority++<br>				<span class="hljs-keyword">continue</span> walk<br>			&#125;<br><br>			<span class="hljs-comment">// Check if a child with the next path byte exists</span><br>			<span class="hljs-keyword">for</span> i, c := <span class="hljs-keyword">range</span> []<span class="hljs-type">byte</span>(n.indices) &#123;  <span class="hljs-comment">// 通过索引查找</span><br>				<span class="hljs-keyword">if</span> c == idxc &#123;   <span class="hljs-comment">// 在child中找到位置?   根据path的首字母查索引</span><br>					<span class="hljs-comment">// 增加给定child的优先级,必要时会发生排序,更新索引</span><br>					i = n.incrementChildPrio(i)<br>					<span class="hljs-comment">// 定位到首字母匹配的子节点,继续迭代</span><br>					n = n.children[i]<br>					<span class="hljs-keyword">continue</span> walk<br>				&#125;<br>			&#125;<br>			<span class="hljs-comment">// 否则,插入   索引未查到</span><br>			<span class="hljs-comment">// Otherwise insert it</span><br>			<span class="hljs-keyword">if</span> idxc != <span class="hljs-string">&#x27;:&#x27;</span> &amp;&amp; idxc != <span class="hljs-string">&#x27;*&#x27;</span> &#123;<span class="hljs-comment">//非通配符</span><br>				<span class="hljs-comment">// []byte for proper unicode char conversion, see #65</span><br>				<span class="hljs-comment">// append操作,在最后添加</span><br>				n.indices += <span class="hljs-type">string</span>([]<span class="hljs-type">byte</span>&#123;idxc&#125;)<br>				child := &amp;node&#123;&#125;<br>				<span class="hljs-comment">// 果然,append</span><br>				n.children = <span class="hljs-built_in">append</span>(n.children, child)<br>				<span class="hljs-comment">// 此处可以推测优先级的含义,即包含的子节点的数量</span><br>				n.incrementChildPrio(<span class="hljs-built_in">len</span>(n.indices) - <span class="hljs-number">1</span>)<br>				<span class="hljs-comment">// 迭代..</span><br>				n = child<br>			&#125;<br>			<span class="hljs-comment">// 插入子节点</span><br>			n.insertChild(path, fullPath, handle)<br>			<span class="hljs-keyword">return</span><br>		&#125;<br><br>		<span class="hljs-comment">// Otherwise add handle to current node</span><br>		<span class="hljs-keyword">if</span> n.handle != <span class="hljs-literal">nil</span> &#123;<br>			<span class="hljs-built_in">panic</span>(<span class="hljs-string">&quot;a handle is already registered for path &#x27;&quot;</span> + fullPath + <span class="hljs-string">&quot;&#x27;&quot;</span>)<br>		&#125;<br>		n.handle = handle<br>		<span class="hljs-keyword">return</span><br>	&#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(n *node)</span></span> insertChild(path, fullPath <span class="hljs-type">string</span>, handle Handle) &#123;<br>	<span class="hljs-keyword">for</span> &#123;<br>		<span class="hljs-comment">// Find prefix until first wildcard</span><br>		wildcard, i, valid := findWildcard(path)<br>		<span class="hljs-keyword">if</span> i &lt; <span class="hljs-number">0</span> &#123; <span class="hljs-comment">// No wilcard found</span><br>			<span class="hljs-keyword">break</span><br>		&#125;<br><br>		<span class="hljs-comment">// The wildcard name must not contain &#x27;:&#x27; and &#x27;*&#x27;</span><br>		<span class="hljs-keyword">if</span> !valid &#123;<br>			<span class="hljs-built_in">panic</span>(<span class="hljs-string">&quot;only one wildcard per path segment is allowed, has: &#x27;&quot;</span> +<br>				wildcard + <span class="hljs-string">&quot;&#x27; in path &#x27;&quot;</span> + fullPath + <span class="hljs-string">&quot;&#x27;&quot;</span>)<br>		&#125;<br><br>		<span class="hljs-comment">// Check if the wildcard has a name</span><br>		<span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(wildcard) &lt; <span class="hljs-number">2</span> &#123;   <span class="hljs-comment">// :name</span><br>			<span class="hljs-built_in">panic</span>(<span class="hljs-string">&quot;wildcards must be named with a non-empty name in path &#x27;&quot;</span> + fullPath + <span class="hljs-string">&quot;&#x27;&quot;</span>)<br>		&#125;<br><br>		<span class="hljs-comment">// Check if this node has existing children which would be</span><br>		<span class="hljs-comment">// unreachable if we insert the wildcard here</span><br>		<span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(n.children) &gt; <span class="hljs-number">0</span> &#123;<br>			<span class="hljs-built_in">panic</span>(<span class="hljs-string">&quot;wildcard segment &#x27;&quot;</span> + wildcard +<br>				<span class="hljs-string">&quot;&#x27; conflicts with existing children in path &#x27;&quot;</span> + fullPath + <span class="hljs-string">&quot;&#x27;&quot;</span>)<br>		&#125;<br><br>		<span class="hljs-comment">// param   参数通配符</span><br>		<span class="hljs-keyword">if</span> wildcard[<span class="hljs-number">0</span>] == <span class="hljs-string">&#x27;:&#x27;</span> &#123;<br>			<span class="hljs-keyword">if</span> i &gt; <span class="hljs-number">0</span> &#123;<br>				<span class="hljs-comment">// Insert prefix before the current wildcard</span><br>				n.path = path[:i]<br>				path = path[i:]<br>			&#125;<br><br>			n.wildChild = <span class="hljs-literal">true</span>  <span class="hljs-comment">// 表明该节点支持统配匹配? </span><br>			child := &amp;node&#123;<br>				nType: param,<br>				path:  wildcard,<br>			&#125;<br>			n.children = []*node&#123;child&#125;<br>			n = child   <span class="hljs-comment">// 迭代操作</span><br>			n.priority++  <span class="hljs-comment">// 优先级+1  所以优先级等同于节点的子节点数量</span><br><br>			<span class="hljs-comment">// If the path doesn&#x27;t end with the wildcard, then there</span><br>			<span class="hljs-comment">// will be another non-wildcard subpath starting with &#x27;/&#x27;</span><br>			<span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(wildcard) &lt; <span class="hljs-built_in">len</span>(path) &#123;   <span class="hljs-comment">// 通配符之后还有路径  /p/:name/xxx   windcard==&quot;:name&quot;</span><br>				path = path[<span class="hljs-built_in">len</span>(wildcard):]  <span class="hljs-comment">// 截取path ,让path始终保持为&quot;待处理的路径&quot;</span><br>				child := &amp;node&#123;  <span class="hljs-comment">// 节点优先级=1 </span><br>					priority: <span class="hljs-number">1</span>,<br>				&#125;<br>				<span class="hljs-comment">// 此时n已经经历过n=child,所以此时n是上一步新建立的子节点</span><br>				n.children = []*node&#123;child&#125;<br>				n = child<span class="hljs-comment">// 继续迭代</span><br>				<span class="hljs-keyword">continue</span><br>			&#125;<br><br>			<span class="hljs-comment">// Otherwise we&#x27;re done. Insert the handle in the new leaf</span><br>			<span class="hljs-comment">// 否则处理完path,完成插入操作,绑定handle</span><br>			n.handle = handle<br>			<span class="hljs-keyword">return</span><br>		&#125;  <span class="hljs-comment">// end param</span><br><br>		<span class="hljs-comment">// catchAll</span><br>		<span class="hljs-keyword">if</span> i+<span class="hljs-built_in">len</span>(wildcard) != <span class="hljs-built_in">len</span>(path) &#123;<br>			<span class="hljs-built_in">panic</span>(<span class="hljs-string">&quot;catch-all routes are only allowed at the end of the path in path &#x27;&quot;</span> + fullPath + <span class="hljs-string">&quot;&#x27;&quot;</span>)<br>		&#125;<br><br>		<span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(n.path) &gt; <span class="hljs-number">0</span> &amp;&amp; n.path[<span class="hljs-built_in">len</span>(n.path)<span class="hljs-number">-1</span>] == <span class="hljs-string">&#x27;/&#x27;</span> &#123;<br>			<span class="hljs-built_in">panic</span>(<span class="hljs-string">&quot;catch-all conflicts with existing handle for the path segment root in path &#x27;&quot;</span> + fullPath + <span class="hljs-string">&quot;&#x27;&quot;</span>)<br>		&#125;<br><br>		<span class="hljs-comment">// Currently fixed width 1 for &#x27;/&#x27;</span><br>		i--<br>		<span class="hljs-keyword">if</span> path[i] != <span class="hljs-string">&#x27;/&#x27;</span> &#123;<br>			<span class="hljs-built_in">panic</span>(<span class="hljs-string">&quot;no / before catch-all in path &#x27;&quot;</span> + fullPath + <span class="hljs-string">&quot;&#x27;&quot;</span>)<br>		&#125;<br><br>		n.path = path[:i]<br><br>		<span class="hljs-comment">// First node: catchAll node with empty path</span><br>		child := &amp;node&#123;<br>			wildChild: <span class="hljs-literal">true</span>,<br>			nType:     catchAll,<br>		&#125;<br>		n.children = []*node&#123;child&#125;<br>		n.indices = <span class="hljs-type">string</span>(<span class="hljs-string">&#x27;/&#x27;</span>)<br>		n = child  <span class="hljs-comment">//迭代 n指向新建的节点</span><br>		n.priority++<br><br>		<span class="hljs-comment">// Second node: node holding the variable   二级节点</span><br>		child = &amp;node&#123;<br>			path:     path[i:],<br>			nType:    catchAll,<br>			handle:   handle,<br>			priority: <span class="hljs-number">1</span>,<br>		&#125;<br>		n.children = []*node&#123;child&#125;<br><br>		<span class="hljs-keyword">return</span><br>	&#125;  <span class="hljs-comment">// end for</span><br><br>	<span class="hljs-comment">// If no wildcard was found, simply insert the path and handle</span><br>	<span class="hljs-comment">// 无需通配符处理</span><br>	n.path = path<br>	n.handle = handle<br>&#125;<br><br><span class="hljs-comment">// Returns the handle registered with the given path (key). The values of</span><br><span class="hljs-comment">// wildcards are saved to a map.</span><br><span class="hljs-comment">// If no handle can be found, a TSR (trailing slash redirect) recommendation is</span><br><span class="hljs-comment">// made if a handle exists with an extra (without the) trailing slash for the</span><br><span class="hljs-comment">// given path.</span><br><span class="hljs-comment">// 返回给定路径对应的handle,若不存在handle,</span><br><span class="hljs-comment">// 而给定路径+&#x27;/&#x27; 这个路径具有注册的handle,则返回 &quot;path/&quot;对应的handle</span><br><span class="hljs-comment">// 这意思是:不用关系url结尾的斜杠咯????</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(n *node)</span></span> getValue(path <span class="hljs-type">string</span>, params <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> *Params) (handle Handle, ps *Params, tsr <span class="hljs-type">bool</span>) &#123;<br>walk: <span class="hljs-comment">// Outer loop for walking the tree</span><br>	<span class="hljs-keyword">for</span> &#123;<br>		prefix := n.path   <span class="hljs-comment">// 前缀  从根节点开始递归查找</span><br>		<span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(path) &gt; <span class="hljs-built_in">len</span>(prefix) &#123;<br>			<span class="hljs-keyword">if</span> path[:<span class="hljs-built_in">len</span>(prefix)] == prefix &#123;  <span class="hljs-comment">// 前缀匹配</span><br>				path = path[<span class="hljs-built_in">len</span>(prefix):]   <span class="hljs-comment">// path截断,毕竟前缀由n存储了,n的子节点不需要包含公共前缀</span><br><br>				<span class="hljs-comment">// If this node does not have a wildcard (param or catchAll)</span><br>				<span class="hljs-comment">// child, we can just look up the next child node and continue</span><br>				<span class="hljs-comment">// to walk down the tree</span><br>				<span class="hljs-keyword">if</span> !n.wildChild &#123;<br>					idxc := path[<span class="hljs-number">0</span>]  <span class="hljs-comment">// 首字母</span><br>					<span class="hljs-comment">// 根据索引查找  这里可知,索引是唯一的</span><br>					<span class="hljs-keyword">for</span> i, c := <span class="hljs-keyword">range</span> []<span class="hljs-type">byte</span>(n.indices) &#123;<br>						<span class="hljs-keyword">if</span> c == idxc &#123;<br>							<span class="hljs-comment">// 从匹配的这个子节点开始继续walk(遍历树)</span><br>							n = n.children[i]<br>							<span class="hljs-keyword">continue</span> walk<br>						&#125;<br>					&#125;<br><br>					<span class="hljs-comment">// Nothing found.</span><br>					<span class="hljs-comment">// We can recommend to redirect to the same URL without a</span><br>					<span class="hljs-comment">// trailing slash if a leaf exists for that path.</span><br>					<span class="hljs-comment">// 索引中不存在</span><br>					<span class="hljs-comment">// if a leaf exists for that path. 这句话的意思是 只有叶子节点才有handle咯???</span><br>					tsr = (path == <span class="hljs-string">&quot;/&quot;</span> &amp;&amp; n.handle != <span class="hljs-literal">nil</span>)<br>					<span class="hljs-keyword">return</span><br>				&#125;<br><br>				<span class="hljs-comment">// Handle wildcard child</span><br>				<span class="hljs-comment">// n.wildChild == true 即child中包含通配符</span><br>				n = n.children[<span class="hljs-number">0</span>]<br>				<span class="hljs-keyword">switch</span> n.nType &#123;<br>				<span class="hljs-keyword">case</span> param: <span class="hljs-comment">// 参数通配符 /p/:name/xxx</span><br>					<span class="hljs-comment">// Find param end (either &#x27;/&#x27; or path end)</span><br>					<span class="hljs-comment">// 寻找参数</span><br>					end := <span class="hljs-number">0</span><br>					<span class="hljs-comment">// 遇到/停止</span><br>					<span class="hljs-keyword">for</span> end &lt; <span class="hljs-built_in">len</span>(path) &amp;&amp; path[end] != <span class="hljs-string">&#x27;/&#x27;</span> &#123;<br>						end++<br>					&#125;<br><br>					<span class="hljs-comment">// Save param value</span><br>					<span class="hljs-comment">// 保存参数值  </span><br>					<span class="hljs-keyword">if</span> params != <span class="hljs-literal">nil</span> &#123;<br>						<span class="hljs-comment">// ps 是返回值</span><br>						<span class="hljs-keyword">if</span> ps == <span class="hljs-literal">nil</span> &#123;<br>							ps = params()<br>						&#125;<br>						<span class="hljs-comment">// Expand slice within preallocated capacity</span><br>						<span class="hljs-comment">// 在预分配容量的切片上扩展</span><br>						i := <span class="hljs-built_in">len</span>(*ps)<br>						*ps = (*ps)[:i+<span class="hljs-number">1</span>]   <span class="hljs-comment">// 发生扩容了吧</span><br>						(*ps)[i] = Param&#123;  <span class="hljs-comment">//新增一个变量</span><br>							Key:   n.path[<span class="hljs-number">1</span>:], <br>							Value: path[:end],<br>						&#125;<br>					&#125;<br><br>					<span class="hljs-comment">// We need to go deeper!</span><br>					<span class="hljs-comment">// case param 中</span><br>					<span class="hljs-comment">// 参数后面还有path</span><br>					<span class="hljs-keyword">if</span> end &lt; <span class="hljs-built_in">len</span>(path) &#123;<br>						<span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(n.children) &gt; <span class="hljs-number">0</span> &#123;  <span class="hljs-comment">// 遍历子节点</span><br>							path = path[end:]<br>							n = n.children[<span class="hljs-number">0</span>]   <span class="hljs-comment">// 进入下一层</span><br>							<span class="hljs-keyword">continue</span> walk<br>						&#125;<br><br>						<span class="hljs-comment">// ... but we can&#x27;t  // tsr trailing slash redirect</span><br>						tsr = (<span class="hljs-built_in">len</span>(path) == end+<span class="hljs-number">1</span>)   <span class="hljs-comment">// 尾斜杠</span><br>						<span class="hljs-keyword">return</span><br>					&#125;<br>					<span class="hljs-comment">// handle是返回值  </span><br>					<span class="hljs-comment">// n.handle不为空,则匹配结束,已经到达叶子节点</span><br>					<span class="hljs-keyword">if</span> handle = n.handle; handle != <span class="hljs-literal">nil</span> &#123;<br>						<span class="hljs-keyword">return</span><br>					&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(n.children) == <span class="hljs-number">1</span> &#123; <br>						<span class="hljs-comment">// No handle found. Check if a handle for this path + a</span><br>						<span class="hljs-comment">// trailing slash exists for TSR recommendation</span><br>						<span class="hljs-comment">// 检测&quot;path/&quot;是否存在handle</span><br>						n = n.children[<span class="hljs-number">0</span>]<br>						tsr = (n.path == <span class="hljs-string">&quot;/&quot;</span> &amp;&amp; n.handle != <span class="hljs-literal">nil</span>) || (n.path == <span class="hljs-string">&quot;&quot;</span> &amp;&amp; n.indices == <span class="hljs-string">&quot;/&quot;</span>)<br>					&#125;<br><br>					<span class="hljs-keyword">return</span><br><br>				<span class="hljs-keyword">case</span> catchAll:  <span class="hljs-comment">//catchAll 通配符结尾的路由</span><br>					<span class="hljs-comment">// Save param value</span><br>					<span class="hljs-keyword">if</span> params != <span class="hljs-literal">nil</span> &#123;<br>						<span class="hljs-keyword">if</span> ps == <span class="hljs-literal">nil</span> &#123;<br>							ps = params()<br>						&#125;<br>						<span class="hljs-comment">// Expand slice within preallocated capacity</span><br>						i := <span class="hljs-built_in">len</span>(*ps)<br>						*ps = (*ps)[:i+<span class="hljs-number">1</span>]<br>						(*ps)[i] = Param&#123;<br>							Key:   n.path[<span class="hljs-number">2</span>:],<br>							Value: path,<br>						&#125;<br>					&#125;<br><br>					handle = n.handle<br>					<span class="hljs-keyword">return</span><br><br>				<span class="hljs-keyword">default</span>:<br>					<span class="hljs-built_in">panic</span>(<span class="hljs-string">&quot;invalid node type&quot;</span>)<br>				&#125;<br>			&#125;<br>		&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> path == prefix &#123;<br>			<span class="hljs-comment">// We should have reached the node containing the handle.</span><br>			<span class="hljs-comment">// Check if this node has a handle registered.</span><br>			<span class="hljs-comment">// 检测当前节点是否存在注册的handle</span><br>			<span class="hljs-keyword">if</span> handle = n.handle; handle != <span class="hljs-literal">nil</span> &#123;<br>				<span class="hljs-keyword">return</span><br>			&#125;<br><br>			<span class="hljs-comment">// If there is no handle for this route, but this route has a</span><br>			<span class="hljs-comment">// wildcard child, there must be a handle for this path with an</span><br>			<span class="hljs-comment">// additional trailing slash</span><br>			<span class="hljs-comment">// 如果该路径没有注册的handle,但是存在一个通配符child,则&quot;path/&quot;会存在一个handle</span><br>			<span class="hljs-keyword">if</span> path == <span class="hljs-string">&quot;/&quot;</span> &amp;&amp; n.wildChild &amp;&amp; n.nType != root &#123;<br>				tsr = <span class="hljs-literal">true</span><br>				<span class="hljs-keyword">return</span><br>			&#125;<br><br>			<span class="hljs-comment">// No handle found. Check if a handle for this path + a</span><br>			<span class="hljs-comment">// trailing slash exists for trailing slash recommendation</span><br>			<span class="hljs-keyword">for</span> i, c := <span class="hljs-keyword">range</span> []<span class="hljs-type">byte</span>(n.indices) &#123;<br>				<span class="hljs-keyword">if</span> c == <span class="hljs-string">&#x27;/&#x27;</span> &#123;<br>					n = n.children[i]<br>					tsr = (<span class="hljs-built_in">len</span>(n.path) == <span class="hljs-number">1</span> &amp;&amp; n.handle != <span class="hljs-literal">nil</span>) ||<br>						(n.nType == catchAll &amp;&amp; n.children[<span class="hljs-number">0</span>].handle != <span class="hljs-literal">nil</span>)<br>					<span class="hljs-keyword">return</span><br>				&#125;<br>			&#125;<br>			<span class="hljs-keyword">return</span><br>		&#125;<br><br>		<span class="hljs-comment">// Nothing found. We can recommend to redirect to the same URL with an</span><br>		<span class="hljs-comment">// extra trailing slash if a leaf exists for that path</span><br>		<span class="hljs-comment">// 一无所获,+个尾斜杠试试</span><br>		tsr = (path == <span class="hljs-string">&quot;/&quot;</span>) ||<br>			(<span class="hljs-built_in">len</span>(prefix) == <span class="hljs-built_in">len</span>(path)+<span class="hljs-number">1</span> &amp;&amp; prefix[<span class="hljs-built_in">len</span>(path)] == <span class="hljs-string">&#x27;/&#x27;</span> &amp;&amp;<br>				path == prefix[:<span class="hljs-built_in">len</span>(prefix)<span class="hljs-number">-1</span>] &amp;&amp; n.handle != <span class="hljs-literal">nil</span>)<br>		<span class="hljs-keyword">return</span><br>	&#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>
<h2 id="6-小结"><a class="markdownIt-Anchor" href="#6-小结"></a> 6 小结</h2>
<p>基本上 httprouter 核心代码都分析完了，个人觉得里面还是有很多设计很巧妙的点的</p>
<ul>
<li>第一点肯定是基数树的运用了，基数树比常规的字典树的查询性能更佳（节点深度更小）并且占的内存也会小一些</li>
<li>第二点就是基数树的实现上，并没有用到递归，而是打了个标签（递归需要频繁的创建销毁栈，性能相对 httprouter 实现会差一些）</li>
<li>第三点感觉 httprouter 里面的 check 还是很精细的，有一些不可能出现的 case 也会加一些 check（比如一开头的检查是否实现了对应接口var _ http.Handler = New()）</li>
<li>第四点 indices 的使用非常巧妙，因为在基数树中，子节点的首字母不可能相同，把子节点的首字母拼成一个字符串来做处理</li>
</ul>
<p><strong>不足</strong> -------路由冲突</p>
<blockquote>
<p>定义了</p>
<p>先有/hello/name</p>
<p>后有/hello/:name----&gt;冲突</p>
</blockquote>
<h2 id="7-路由冲突问题"><a class="markdownIt-Anchor" href="#7-路由冲突问题"></a> 7 路由冲突问题</h2>
<blockquote>
<p>panic: wildcard route ‘:articleID’ conflicts with existing children in path ‘/articles/:articleID’</p>
</blockquote>
<p>httprouter 为了性能优化使用了<strong>显式匹配</strong>，这就导致了很多<strong>通配符与具体路由</strong>产生冲突。</p>
<p>如下列路由就会冲突：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs bash">GET /articles/info<br>GET /articles/:articleID<br></code></pre></td></tr></table></figure>
<h2 id="解决方案"><a class="markdownIt-Anchor" href="#解决方案"></a> 解决方案</h2>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://hanggi.me/post/golang/wildcard-conflict/">gin 路由冲突问题解决方法 | Hanggi - NGNL</a></p>
</blockquote>
<h3 id="1-修改路由规则"><a class="markdownIt-Anchor" href="#1-修改路由规则"></a> 1. 修改路由规则</h3>
<p>对于路由规则不是很复杂的项目，可以使用规避传统路由规则的方法，如：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs bash">GET /articles/info<br>GET /article/:articleId<br></code></pre></td></tr></table></figure>
<p>但是这种方法违背了我们常用的 RESTful API 规则，非常不舒服。在项目比较大比较负责的情况下就会非常混乱。</p>
<h3 id="2-特定路由参数分支"><a class="markdownIt-Anchor" href="#2-特定路由参数分支"></a> 2. 特定路由参数分支</h3>
<p>一种简单的解决方法就是在通配符外面包裹一层判断语句。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs go">router.GET(<span class="hljs-string">&quot;/v1/users/:userID&quot;</span>, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(c *gin.Context)</span></span> &#123;<br>    <span class="hljs-keyword">if</span> c.Param(<span class="hljs-string">&quot;userID&quot;</span>) == <span class="hljs-string">&quot;info&quot;</span> &#123;<br>        ...<br>    &#125; <span class="hljs-keyword">else</span> &#123;<br>        ...<br>    &#125;<br>&#125;)<br></code></pre></td></tr></table></figure>
<p>如果觉得这种写法不易阅读，还可以使用如下判断语句：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs go">router.GET(<span class="hljs-string">&quot;/v1/users/:userID&quot;</span>, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(c *gin.Context)</span></span> &#123;<br>    <span class="hljs-keyword">if</span> strings.HasPrefix(c.Request.RequestURI, <span class="hljs-string">&quot;/v1/users/info&quot;</span>) &#123;<br>        ...<br>        <span class="hljs-keyword">return</span><br>    &#125;<br>    ...<br>&#125;)<br></code></pre></td></tr></table></figure>
<h3 id="3-多级路由分支"><a class="markdownIt-Anchor" href="#3-多级路由分支"></a> 3. 多级路由分支</h3>
<p>httprouter 中<strong>通配符接通配符</strong>是可以被正常识别的，所以在多级路由中可以使用以下方法:</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs go">router.GET(<span class="hljs-string">&quot;/v1/images/:path1&quot;</span>, GetHandler)           <span class="hljs-comment">//      /v1/images/detail</span><br>router.GET(<span class="hljs-string">&quot;/v1/images/:path1/:path2&quot;</span>, GetHandler)    <span class="hljs-comment">//      /v1/images/&lt;id&gt;/history</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">GetHandler</span><span class="hljs-params">(c *gin.Context)</span></span> &#123;<br>    path1 := c.Param(<span class="hljs-string">&quot;path1&quot;</span>)<br>    path2 := c.Param(<span class="hljs-string">&quot;path2&quot;</span>)<br><br>    <span class="hljs-keyword">if</span> path1 == <span class="hljs-string">&quot;detail&quot;</span> &amp;&amp; path2 == <span class="hljs-string">&quot;&quot;</span> &#123;<br>        Detail(c)<br>    &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> path1 != <span class="hljs-string">&quot;&quot;</span> &amp;&amp; path2 == <span class="hljs-string">&quot;history&quot;</span> &#123;<br>        imageId := path1<br>        History(c, imageId)<br>    &#125; <span class="hljs-keyword">else</span> &#123;<br>        HandleHttpError(c, NewHttpError(<span class="hljs-number">404</span>, <span class="hljs-string">&quot;Page not found&quot;</span>))<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="4-使用-号进行通配"><a class="markdownIt-Anchor" href="#4-使用-号进行通配"></a> 4. 使用 <code>*</code> 号进行通配</h3>
<p>httprouter 提供 <code>*</code> 号匹配，匹配效果如下：</p>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs awk"><span class="hljs-regexp">/users/</span>*action<br><br>    <span class="hljs-regexp">/users/</span>                     action = <span class="hljs-string">&quot;&quot;</span><br>    <span class="hljs-regexp">/users/</span>somefile.go          action = <span class="hljs-string">&quot;somefile.go&quot;</span><br>    <span class="hljs-regexp">/users/</span>subdir<span class="hljs-regexp">/somefile.go   action = &quot;subdir/</span>somefile.go<span class="hljs-string">&quot;</span><br></code></pre></td></tr></table></figure>
<h2 id="总结"><a class="markdownIt-Anchor" href="#总结"></a> 总结</h2>
<p>httprouter 在提供高性能的同时也确实带来了诸多不便，以上几种方法不能说完美，但应该可以满足大部分 RESTful API 的规范要求。</p>
<p>更好等方法其实是————不要用 wildcard。。。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/Golang/" class="category-chain-item">Golang</a>
  
  
    <span>></span>
    
  <a href="/categories/Golang/Gin/" class="category-chain-item">Gin</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E5%89%8D%E7%BC%80%E6%A0%91/">#前缀树</a>
      
        <a href="/tags/%E8%B7%AF%E7%94%B1/">#路由</a>
      
        <a href="/tags/httprouter/">#httprouter</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>httprouter</div>
      <div>http://example.com/2022/04/18/20220418-httprouter/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>叶飞</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年4月18日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/04/20/20220420-Go%E6%89%93%E5%8D%B0%E5%B8%A6%E8%BD%AC%E4%B9%89%E5%AD%97%E7%AC%A6%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2/" title="Go打印带转义字符的字符串">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Go打印带转义字符的字符串</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/04/17/20220417-Gin%E5%8A%A8%E6%80%81%E8%B7%AF%E7%94%B1/" title="Gin动态路由">
                        <span class="hidden-mobile">Gin动态路由</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  


  
  









    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  
      <script>
        if (!window.MathJax) {
          window.MathJax = {
            tex    : {
              inlineMath: { '[+]': [['$', '$']] }
            },
            loader : {
              load: ['ui/lazy']
            },
            options: {
              renderActions: {
                insertedScript: [200, () => {
                  document.querySelectorAll('mjx-container').forEach(node => {
                    let target = node.parentNode;
                    if (target.nodeName.toLowerCase() === 'li') {
                      target.parentNode.classList.add('has-jax');
                    }
                  });
                }, '', false]
              }
            }
          };
        } else {
          MathJax.startup.document.state(0);
          MathJax.texReset();
          MathJax.typeset();
          MathJax.typesetPromise();
        }
      </script>
    

  <script  src="https://lib.baomitu.com/mathjax/3.2.1/es5/tex-mml-chtml.js" ></script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="/js/leancloud.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
